package com.yfbao.horizon.utils;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.common.collect.Maps;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class CacheUtil {
    //记录保存时间很多的一类缓存，比如保存10s,5s时长的缓存；默认队列一般较短（100），无需主动清理，一般依赖自动过期进行淘汰
    private static Map<String, Cache<String, Object>> specialShortTimeCacheMap = Maps.newHashMap();
    private static Integer shortDefaultLength = 100;
    private static final Random random = new Random();

    /**
     * 获取快速过期缓存
     * @param cacheName
     * @param key
     * @return
     */
    public static Object getShortTimeCache(String cacheName,String key){
        Cache<String, Object> stringObjectCache = specialShortTimeCacheMap.get(cacheName);
        if(stringObjectCache==null){
            return null;
        }
        return stringObjectCache.getIfPresent(key);
    }

    /**
     * 设置快速过期缓存
     * @param cacheName 缓存类型名称
     * @param key  缓存名称
     * @param value  缓存值
     * @param timeout 缓存类型的统一过期时间(单位s,一般不超过60s,传null时默认10s)
     * @return
     */
    public static void putShortTimeCache(String cacheName,String key,Object value,Long timeout){
        Cache<String, Object> stringObjectCache = specialShortTimeCacheMap.get(cacheName);
        if(timeout ==null){
            timeout =10L;
        }
        if(stringObjectCache ==null){
            synchronized (shortDefaultLength){
                stringObjectCache = specialShortTimeCacheMap.get(cacheName);
                if(stringObjectCache ==null){
                    stringObjectCache = Caffeine.newBuilder().expireAfterWrite(timeout*1000+getIntRandom(500), TimeUnit.MILLISECONDS).maximumSize(shortDefaultLength).weakKeys().weakValues().build();
                    specialShortTimeCacheMap.put(cacheName,stringObjectCache);
                }
            }
        }
        stringObjectCache.put(key,value);
    }


    /**
     * 获取随机数
     * @param num
     * @return
     */
    public static int getIntRandom(Integer num){
        return random.nextInt(num);
    }
}
